//
//  ByMyInformationVC.m
//  recordworktool_ios
//
//  Created by mc on 2017/12/11.
//  Copyright © 2017年 ZhangZhanbin. All rights reserved.
//

#import "ByMyInformationVC.h"
#import "ByNickNameUpdateVC.h"

#import "ByGenderSelectView.h"
#import "ByHourDatePicker.h"
#import "ByLoginVC.h"

#import "ByOtherCityObject.h"

@interface ByMyInformationVC ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate, UINavigationControllerDelegate,UIActionSheetDelegate,UIPickerViewDataSource,UIPickerViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *itemsAry;
@property (nonatomic, strong) UIImageView *imageView;

@property (nonatomic, strong) ZKBombView *dateView;
@property (nonatomic, strong) NSArray *dateArray;
@property (nonatomic, copy)  NSString *gender;

@property (nonatomic, strong) ZKBombView *picker;

@property (nonatomic, strong) ByOtherCityObject *cityObject;

@end

@implementation ByMyInformationVC


#pragma mark - getter
-(NSMutableArray *)provinceListArray{
    
    if (_provinceListArray == nil) {
        _provinceListArray = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return _provinceListArray;
}

-(NSMutableArray *)cityListArray{
    
    if (_cityListArray == nil) {
        _cityListArray = [[NSMutableArray alloc] initWithCapacity:0];
        
    }
    return _cityListArray;
}

-(NSMutableArray *)areaListArray{
    
    if (_areaListArray == nil) {
        _areaListArray = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return _areaListArray;
}



#pragma mark - 创建数据
-(void)_initCityData{
    
    // 获得全部省的数组
    [self.provinceListArray addObjectsFromArray:[ByCoreAddressSqlite3 getAllProvinceModel]];
    ByCoreProvinceModel *province = [self.provinceListArray firstObject];
    
    // 获得全部城市的数组
    [self.cityListArray addObjectsFromArray:[ByCoreAddressSqlite3 getAllCityModelWithProvinceID:province.provinceID]];
    ByCoreCityModel *city = [self.cityListArray firstObject];
    
    // 获得全部区的数组
    [self.areaListArray addObjectsFromArray:[ByCoreAddressSqlite3 getAllAreaModelWithCityID:city.cityID]];
    
    // 总数据
    self.dataArray =[[NSMutableArray alloc] init];
    [self.dataArray addObject:self.provinceListArray];
    [self.dataArray addObject:self.cityListArray];
    [self.dataArray addObject:self.areaListArray];
}

- (ZKBombView *)picker {
    
    if (!_picker) {
        
        _picker = [[ZKBombView alloc] init];
        _picker.positionMode = ZKBombPositionModeBottom;
        
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 300)];
        view.backgroundColor = [UIColor whiteColor];
        
        view.backgroundColor = [UIColor redColor];
        
        
        
        UIButton *determineBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [view addSubview:determineBtn];
        [determineBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(view).offset(0);
            make.bottom.equalTo(view).offset(0);
            make.right.equalTo(view).offset(0);
            make.left.equalTo(view).offset(0);
            make.height.mas_equalTo(@50);
        }];
        
        
        [determineBtn setTitle:@"确定" forState:UIControlStateNormal];
        determineBtn.backgroundColor = BY_THEME_COLOR;
        [determineBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [determineBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        
        [self _initCityData]; // 从数据库中读取获得城市数据
        
        self.pickerView = [[UIPickerView alloc] init];
        self.pickerView.delegate = self;
        self.pickerView.dataSource = self;
        self.pickerView.backgroundColor = [UIColor whiteColor];
        [view addSubview: self.pickerView];
        
        [self.pickerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(view).offset(0);
            make.top.equalTo(view).offset(0);
            make.bottom.equalTo(determineBtn.mas_top).offset(0);
            make.right.equalTo(view).offset(0);
        }];
        
        _picker.contentView = view;
    }
    return _picker;
    
}


- (void)btnAction:(UIButton *)btn{
    [self.picker remove];
    self.picker = nil;
    
    UITableViewCell *cell6 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:6 inSection:0]];
    UITextField *TF6 = [cell6 viewWithTag:100];
    if ([self.cityObject.city isEqualToString:@"县"] || [self.cityObject.city isEqualToString:@"市辖区"]) {
       self.cityObject.fullAddress = [NSString stringWithFormat:@"%@%@", self.cityObject.province,self.cityObject.area];
    }else if ([self.cityObject.area isEqualToString:@"市辖区"]) {
        self.cityObject.fullAddress = [NSString stringWithFormat:@"%@%@", self.cityObject.province,self.cityObject.city];
    }
    
    TF6.text = self.cityObject.fullAddress;
}



- (ZKBombView *)dateView{
    if (_dateView == nil) {
        _dateView = [[ZKBombView alloc] init];
        _dateView.positionMode = ZKBombPositionModeBottom;
        _dateView.popMode = ZKBombPopModeBottom;
        _dateView.usePickerTitleForCustomContentMode = YES;
        UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,216)];
        _dateView.contentView = contentView;
        _dateView.contentMode = ZKBombContentModeCustom;
        _dateView.title = @"选择时间";
        
        ByHourDatePicker *picker = [[ByHourDatePicker alloc] init];
        picker.frame = contentView.bounds;
        picker.dateDidPicker = ^(NSArray *dateArray){
            self.dateArray = dateArray;
        };
        [contentView addSubview:picker];
        _dateView.removeBlock = ^(){
            NSLog(@"取消");
        };
        __weak typeof(self) weakSelf = self;
        _dateView.customTapOk = ^(){
            NSLog(@"OK");
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:5 inSection:0];
            [weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        };
        
        
        
    }
    return _dateView;
}



- (NSArray *)itemsAry{
    if (_itemsAry == nil) {
        _itemsAry = @[@[@"头像",@"昵称",@"姓名",@"性别",@"民族",@"生日",@"家乡"],@[@"工程类型",@"工种",@"工龄"]];
    }
    return _itemsAry;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addLeftBackBarButtonItem];
    self.title = @"我的信息";
    
    [self initViews];
    
    [self addBYItemviews:@[@"保存"] mode:ByNavigationItemModeText  position:ByNavigationItemPositionModeRight];
    // Do any additional setup after loading the view.
}

- (void)rightItemsAction:(NSInteger)rightIndex{
    NSLog(@"保存");
    UITableViewCell *cell1 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    UITextField *TF1 = [cell1 viewWithTag:100];
    UITableViewCell *cell2 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    UITextField *TF2 = [cell2 viewWithTag:100];
   
    UITableViewCell *cell4 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:4 inSection:0]];
    UITextField *TF4 = [cell4 viewWithTag:100];
    UITableViewCell *cell5 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:5 inSection:0]];
    UITextField *TF5 = [cell5 viewWithTag:100];

    UITableViewCell *cell6 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:6 inSection:0]];
    UITextField *TF6 = [cell6 viewWithTag:100];
    
    UITableViewCell *cell7 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
    UITextField *TF7 = [cell7 viewWithTag:100];
    UITableViewCell *cell8 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:1]];
    UITextField *TF8 = [cell8 viewWithTag:100];
    UITableViewCell *cell9 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:1]];
    UITextField *TF9 = [cell9 viewWithTag:100];
    ByNetParamsModel *paramsModel = [[ByNetParamsModel alloc] init];
    NSInteger count = 0;
    if (![BY_USER.nickname isEqualToString:TF1.text]) {
        paramsModel.nickname = TF1.text;
        count = count + 1;
    }
    if (![BY_USER.realname isEqualToString:TF2.text]) {
        paramsModel.realname = TF2.text;
        count = count + 1;
    }
    if (![BY_USER.nation isEqualToString:TF4.text]) {
        paramsModel.nation = TF4.text;
        count = count + 1;
    }
    
    if (![BY_USER.hometown isEqualToString:TF6.text]) {
        paramsModel.hometown = TF6.text;
        count = count + 1;
    }
    
    if (![BY_USER.profession isEqualToString:TF7.text]) {
        paramsModel.profession = TF7.text;
        count = count + 1;
    }
    
    if (![BY_USER.works_cate isEqualToString:TF8.text]) {
        paramsModel.works_cate = TF8.text;
        count = count + 1;
    }
    
    if (![BY_USER.working_years isEqualToString:TF9.text]) {
        paramsModel.working_years = TF9.text;
        count = count + 1;
    }
    
    if (self.gender && self.gender.length > 0) {
        if (BY_USER.sex.integerValue == 0) {
            NSString *sex = @"女";
            if (![self.gender isEqualToString:sex]) {
                paramsModel.sex = @"1";
                count = count + 1;
            }
        }else{
            NSString *sex = @"男";
            if ([self.gender isEqualToString:sex]) {
                paramsModel.sex = @"0";
                count = count + 1;
            }
        }
       
    }
    
    if (self.dateArray && self.dateArray.count > 0) {
        NSString *month;
        NSString *day;
        if ([self.dateArray[1] integerValue] < 10) {
            month = [NSString stringWithFormat:@"0%@",self.dateArray[1]];
        }else{
            month = self.dateArray[1];
        }
        if ([self.dateArray[2] integerValue] < 10) {
            day = [NSString stringWithFormat:@"0%@",self.dateArray[2]];
        }else{
            day = self.dateArray[2];
        }
        NSString *time = [NSString stringWithFormat:@"%@-%@-%@",self.dateArray[0], month, day];
        paramsModel.birthday = [NSString stringWithFormat:@"%ld", [self timeSwitchTimestamp:time andFormatter:@"YYYY-MM-dd"]];
        count = count + 1;
    }
    ByModelUser *user = [ByCacheUser getUserInfo];
    paramsModel.uid = user.uid;
    
    if (count == 0) {
        return;
    }
    
    [ByCoreToolAlert showLoadind:@"保存中" hasMasker:YES];
    [ByApiUser userUpdate:paramsModel success:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showSuccessWithText:@"保存成功"];
        [self dismissViewControllerAnimated:YES completion:nil];
        
        if (![BY_USER.nickname isEqualToString:TF1.text]) {
            user.nickname = TF1.text;
        }
        if (![BY_USER.realname isEqualToString:TF2.text]) {
            user.realname = TF2.text;
        }
        if (![BY_USER.nation isEqualToString:TF4.text]) {
            user.nation = TF4.text;
        }
        
        if (![BY_USER.hometown isEqualToString:TF6.text]) {
            user.hometown = TF6.text;
        }
        
        if (![BY_USER.profession isEqualToString:TF7.text]) {
            user.profession = TF7.text;
        }
        
        if (![BY_USER.works_cate isEqualToString:TF8.text]) {
            user.works_cate = TF8.text;
        }
        
        if (![BY_USER.working_years isEqualToString:TF9.text]) {
            user.working_years = TF9.text;
        }
        if (self.dateArray.count > 0) {
            user.birthday = paramsModel.birthday;
        }
        
        if (paramsModel.sex) {
            user.sex = paramsModel.sex;
        }
        [ByCacheUser setUserInfo:user];
        
    } failure:^(ByNetBaseResult *result) {
        
        
        [ByCoreToolAlert showFailureWithText:result.msg];
    }];
}

-(NSInteger)timeSwitchTimestamp:(NSString *)formatTime andFormatter:(NSString *)format{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:format]; //(@"YYYY-MM-dd") ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate* date = [formatter dateFromString:formatTime];
    //时间转时间戳的方法:
    NSInteger timeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]] integerValue];
    NSLog(@"时间戳 = %ld", timeSp);
    return timeSp;
}




- (void)initViews{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - STATUS_NAV) style:UITableViewStyleGrouped];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 80)];
    UIButton *exitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [footer addSubview:exitBtn];
    [exitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(footer).offset(60);
        make.right.equalTo(footer).offset(-60);
        make.centerY.equalTo(footer).offset(0);
        make.height.mas_equalTo(@40);
    }];
    exitBtn.backgroundColor = GREEN_COLOR;
    [exitBtn setTitle:@"退出登录" forState:UIControlStateNormal];
    [exitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    exitBtn.layer.cornerRadius = 5;
    exitBtn.titleLabel.font = FONT(16);
    [exitBtn addTarget:self action:@selector(exitAciton:) forControlEvents:UIControlEventTouchUpInside];
    self.tableView.tableFooterView = footer;
}

- (void)exitAciton:(UIButton *)btn{
    NSLog(@"退出登录");
    [UMessage removeAlias:BY_USER.uid type:@"com.itboye.jigongbao" response:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        NSLog(@"解除 %@=---------%@",responseObject,error);
    }];
    [ByCacheUser setUserInfo:nil];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    ByLoginVC *vc =  [[ByLoginVC alloc] init];
    vc.needReload = YES;
    
    ByBaseNaviController *navi = [[ByBaseNaviController alloc] initWithRootViewController:vc];
    window.rootViewController = navi;
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.itemsAry.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *itemsAry = [self.itemsAry objectAtIndex:section];
    return itemsAry.count;
}


- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellIdentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        UILabel *line = [[UILabel alloc] init];
        [cell addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(cell).offset(0);
            make.right.equalTo(cell).offset(0);
            make.bottom.equalTo(cell).offset(0);
            make.height.mas_offset(@1);
        }];
        line.backgroundColor = BY_LINE_COLOR;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    for (UIView *view in cell.contentView.subviews) {
        [view removeFromSuperview];
    }
    
    
    UILabel *titleLabel = [[UILabel alloc] init];
    [cell.contentView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(cell.contentView).offset(10);
        make.centerY.equalTo(cell.contentView).offset(0);
        make.size.mas_equalTo(CGSizeMake(100, 20));
    }];
    titleLabel.font = FONT(16);
    titleLabel.textColor = TEXT_COLOR;
    titleLabel.text = self.itemsAry[indexPath.section][indexPath.row];
    
    
    if (indexPath.row == 0 && indexPath.section == 0){
        
        UIImageView *imageView = [[UIImageView alloc] init];
        [cell.contentView addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(cell.contentView).offset(0);
            make.right.equalTo(cell.contentView).offset(-10);
            make.size.mas_equalTo(CGSizeMake(35, 35));
        }];
        imageView.layer.cornerRadius = 17.5;
        imageView.layer.masksToBounds = YES;
        [imageView setImageWithURL:[NSURL URLWithString:BOYE_AVATAR_URL(BY_USER.uid)] placeholderImage:DEFAULT_IMAGE completed:nil];
        self.imageView = imageView;
        
        
    }else{
        
        UITextField *textTield = [[UITextField alloc] init];
        [cell.contentView addSubview:textTield];
        [textTield mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(cell.contentView).offset(0);
            make.right.equalTo(cell.contentView).offset(-10);
            make.left.equalTo(titleLabel.mas_right).offset(30);
            make.height.mas_equalTo(@20);
        }];
        textTield.tag = 100;
        textTield.textAlignment = NSTextAlignmentRight;
        
        if (indexPath.row == 3 && indexPath.section == 0){
            textTield.userInteractionEnabled = NO;
            if (BY_USER.sex.integerValue == 0) {
                textTield.text = @"女";
            }else{
                textTield.text = @"男";
            }
            if (self.gender && self.gender.length > 0) {
                textTield.text = self.gender;
            }
            
        }else if (indexPath.row == 5 && indexPath.section == 0){
            textTield.userInteractionEnabled = NO;
            textTield.text = [NSString stringWithFormat:@"%@", [NSDate getDateForStringFotmatWithTimeInterval:BY_USER.birthday.integerValue formatter:@"yyyy-MM-dd"]];
            if (self.dateArray) {
                textTield.text = [NSString stringWithFormat:@"%@-%@-%@", self.dateArray[0],self.dateArray[1],self.dateArray[2]];
            }
            
        }else if (indexPath.section == 0 && indexPath.row == 1){
            
            textTield.text = BY_USER.nickname;
            
        }else if (indexPath.section == 0 && indexPath.row == 2){
            
            textTield.text = BY_USER.realname;
            
        }else if (indexPath.section == 0 && indexPath.row == 4){
            
            textTield.text = BY_USER.nation;
            
        }else if (indexPath.section == 0 && indexPath.row == 6){
            
            textTield.userInteractionEnabled = NO;
            textTield.text = BY_USER.hometown;
            
        }else if (indexPath.section == 1 && indexPath.row == 0){
            
            textTield.text = BY_USER.profession;
            
        }else if (indexPath.section == 1 && indexPath.row == 1){
            
            textTield.text = BY_USER.works_cate;
        }else if (indexPath.section == 1 && indexPath.row == 2){
            
            textTield.text = BY_USER.working_years;
            
        }else if (indexPath.section == 0 && indexPath.row == 3){
            
            textTield.text = BY_USER.realname;
        }
        
    }
    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
   
    
    return cell;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];// 取消选中阴影
    
    if (indexPath.row == 0 && indexPath.section == 0) {
        
            
//            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//
//            // 添加点击动作
//            // 取消
//            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
//            // 相册中
//            UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action)
//                                          {
//                                              [self _choosePhotoFromAlbum];
//                                          }];
//            // 拍照
//            UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action)
//                                           {
//                                               [self _getphotoFromCamera];
//                                           }];
//
//            // Add the actions.
//            [alertController addAction:cancelAction];
//            [alertController addAction:albumAction];
//            [alertController addAction:cameraAction];
//
//            [self presentViewController:alertController animated:YES completion:nil];
        
       
    
    }else if (indexPath.section == 0 && indexPath.row == 1){
        
//        ByNickNameUpdateVC *vc = [[ByNickNameUpdateVC alloc] init];
//        vc.title = @"昵称";
//        [self by_normalPush:vc hasNavi:YES];
        
    }else if (indexPath.section == 0 && indexPath.row == 2){
        
//        ByNickNameUpdateVC *vc = [[ByNickNameUpdateVC alloc] init];
//        vc.title = @"姓名";
//        [self by_normalPush:vc hasNavi:YES];
        
        
    }else if (indexPath.section == 0 && indexPath.row == 3){
        
        [[UIApplication sharedApplication].keyWindow endEditing:YES];
        NSLog(@"性别");
        ByGenderSelectView *view = [[ByGenderSelectView alloc] init];
        view.female = ^(){
            NSLog(@"女");
            self.gender  = @"女";
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:3 inSection:0];
            [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        };
        view.male = ^(){
            
            NSLog(@"男");
            self.gender = @"男";
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:3 inSection:0];
            [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        };
        [view show];
        
    }else if (indexPath.section == 0 && indexPath.row == 5){
        
        [[UIApplication sharedApplication].keyWindow endEditing:YES];
        [self.dateView show];
        
    }else if (indexPath.section == 0 && indexPath.row == 6){
        
        [[UIApplication sharedApplication].keyWindow endEditing:YES];
        self.pickerView = nil;
        ByOtherCityObject *cityObject = [[ByOtherCityObject alloc] init];
        cityObject.fullAddress = @"北京市";
        self.cityObject = cityObject;
        [self.picker show];
        
    }
}
    
#pragma mark - 头像图片选择相关操作
    // 从相册中选择照片
- (void)_choosePhotoFromAlbum
    {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        if (![UIImagePickerController isSourceTypeAvailable:sourceType]) {
            
            [ByCoreToolAlert showOnlyText:@"相机不可用！"];
            return;
        }
        [self _changeToPickerController:sourceType];
    }
    
    // 通过拍照获取照片
- (void)_getphotoFromCamera{
    
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if (![UIImagePickerController isSourceTypeAvailable:sourceType]) {
            
            [ByCoreToolAlert showOnlyText:@"相机不可用！"];
            return;
        }
        [self _changeToPickerController:sourceType];
}
    
    
// 创建并跳转到图片获取界面
- (void)_changeToPickerController:(UIImagePickerControllerSourceType)sourceType{
        //创建图片拾取界面
        UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
        pickerController.delegate = self;
        //设置可编辑
        pickerController.allowsEditing = YES;
        pickerController.sourceType = sourceType;
        pickerController.title = @"头像选择";
        [pickerController.navigationBar setTintColor:[UIColor darkGrayColor]];
        [self presentViewController:pickerController animated:YES completion:nil];
}
    
    //UIImagePickerController代理方法，选取图片之后处理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
    {
        UIImage *editedImage = (UIImage *)[info objectForKey:UIImagePickerControllerEditedImage];
        UIImage *originalImage = (UIImage *)[info objectForKey:UIImagePickerControllerOriginalImage];
        if (editedImage) {
            // 保存到相册
            UIImageWriteToSavedPhotosAlbum(editedImage, nil, nil, nil);
            // 设置成头像
            
            
            
            // 返回“个人”界面
            [self dismissViewControllerAnimated:YES completion:^{
                // 上传图片
                
                [self uploadIcon:editedImage];
            }];
            
        }
        else if (originalImage) {
            // 设置头像
            
            
            // 返回“个人”界面
            [self dismissViewControllerAnimated:YES completion:^{
                // 上传图片
                [self uploadIcon:originalImage];
                
            }];
            
        }
    }
    
#pragma mark - net
- (void)uploadIcon:(UIImage *)icon {
        
        // 上传头像
        [ByCoreToolAlert showLoadind:@"上传中" hasMasker:YES];
        [ByNetBaseApi uploadImage:icon type:@"avatar" success:^(NSArray *success) {
            self.imageView.image = icon;
            NSDictionary *dic = success[0];
            ByModelUser *user = BY_USER;
            user.head = dic[@"id"];
            [ByCacheUser setUserInfo:user];
            [ByCoreToolAlert showSuccessWithText:@"上传成功"];
            [self.tableView reloadData];
        } failure:^(NSURLSessionDataTask *operation, NSError *error) {
            [ByCoreToolAlert showSuccessWithText:error.domain];
        }];
}
    
    
    
#pragma mark - UIActionSheet代理方法（适配iOS8.0以下时使用）
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
        if (actionSheet.tag == 300) {
            // 选择照片
            // 从相册中选择
            if (buttonIndex == 0) {
                [self _choosePhotoFromAlbum];
            }
            // 通过拍照获取
            else if (buttonIndex == 1) {
                [self _getphotoFromCamera];
            }
            
            
        }
}
    
    
 

#pragma mark --- pickView delegate,datasource
// 列数
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 3;
}

// 行数
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return [(NSArray *)[self.dataArray objectAtIndex:component] count];
}

// 每行的标题
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    if (component == 0) {
        ByCoreProvinceModel *province = self.provinceListArray[row];
        return province.province;
        
    } else if (component == 1) {
        ByCoreCityModel *city = self.cityListArray[row];
        return city.city;
        
    } else {
        ByCoreAreaModel *area = self.areaListArray[row];
        return area.area;
    }
}


// 选中单元格
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    if (component == 0) { // 选中第一列（省份）那么第二列和第三列都变为第一行
        
        self.provinceRow = row;
        
        [self getCityData:row]; // 根据选择的省份重新获取城市数组
        [self getAreaData:0]; // 城市数组为当前城市数组中第一个城市的地区数组
        
        self.provinceRow = row;
        self.cityRow = 0;
        self.areaRow = 0;
        
    } else if (component == 1) { // 选中第二列（城市）那么第一列不变，第三列都变为第一行
        
        self.cityRow = row;
        
        [self getAreaData:row]; // 根据选择的城市重新获取地区数组
        
        self.areaRow = 0;
        
        
    } else { // 选中第三列（地区）那么第一列和第二列都变
        
        self.areaRow = row;
    }
    
    [self.pickerView reloadAllComponents];
    
    [self.pickerView selectRow:self.provinceRow inComponent:0 animated:YES];
    [self.pickerView selectRow:self.cityRow inComponent:1 animated:YES];
    [self.pickerView selectRow:self.areaRow inComponent:2 animated:YES];
    
    
    // 每次点击都获取当前的地址
    ByOtherCityObject *cityObject = [self buildCityObject];
    self.cityObject = cityObject;
    // 把当前地址回传到控制器里，设置UI
    NSLog(@"%@ %@ %@ %@", cityObject.province, cityObject.city, cityObject.area, cityObject.fullAddress);
}

// 创建模型
- (ByOtherCityObject *)buildCityObject{
    
    ByOtherCityObject *object = [[ByOtherCityObject alloc] init];
    // 省
    ByCoreProvinceModel *province = self.provinceListArray[self.provinceRow];
    object.province = province.province;
    object.provinceid =  province.provinceID;
    
    // 市
    if (self.cityListArray.count == 0) { // 某省份下没有市了
        object.city = @"";
        object.cityid  =  @"0";
    } else {
        ByCoreCityModel *city = self.cityListArray[self.cityRow];
        object.city = city.city;
        object.cityid  =  city.cityID;
    }
    
    // 地区
    if (self.areaListArray.count == 0) { // 某市中没有地区了
        object.area = @"";
        object.areaid = @"0";
    } else {
        ByCoreAreaModel *area = self.areaListArray[self.areaRow];
        object.areaid = area.areaID;
        object.area = area.area;
    }
    
    object.fullAddress =[NSString stringWithFormat:@"%@%@%@", object.province, object.city, object.area];
    
    return object;
}


#pragma mark  -- 根据provinceID 读取城市列表
- (void)getCityData:(NSInteger )row{
    
    // 当前省份
    ByCoreProvinceModel *province = self.provinceListArray[row];
    [self.cityListArray removeAllObjects];
    [self.cityListArray setArray:[ByCoreAddressSqlite3 getAllCityModelWithProvinceID:province.provinceID]];
    
    
}
#pragma mark  -- 根据cityID 读取地区列表
-(void)getAreaData:(NSInteger )row{
    
    // 如果没有城市，那么地区也对应没有
    if (self.cityListArray.count == 0) {
        [self.areaListArray removeAllObjects];
        return;
    }
    // 当前城市
    ByCoreCityModel *city = self.cityListArray[row];
    [self.areaListArray removeAllObjects];
    [self.areaListArray setArray:[ByCoreAddressSqlite3 getAllAreaModelWithCityID:city.cityID]];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
